<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="用印流水号" prop="sealId">
        <el-input
          v-model="queryParams.sealId"
          placeholder="请输入用印流水号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标题" prop="sealTitle">
        <el-input
          v-model="queryParams.sealTitle"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室意见" prop="deptIdea">
        <el-select v-model="queryParams.deptIdea" placeholder="请选择科室意见">
          <el-option
            v-for="item in deptIdeaOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value"
            @keyup.enter.native="handleQuery"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用印审批人意见" prop="sealIdea">
        <el-select v-model="queryParams.sealIdea" placeholder="请选择用印审批人意见">
          <el-option
            v-for="item in deptIdeaOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value"
            @keyup.enter.native="handleQuery"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['seal:seal:add']"
        >申请
        </el-button>
      </el-col>
      <el-col :span="1.5">

      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['seal:seal:remove']"
        >取消
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['seal:seal:exportOwnSelectedSealList']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border fit v-loading="loading" :data="sealList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column label="用印流水号" width="130" align="center" prop="sealId"/>
      <el-table-column label="申请人姓名" width="90" align="center" prop="userName"/>
      <el-table-column label="申请人部门" width="130" align="center" prop="userDept"/>
      <el-table-column label="申请印章类别" width="200" align="center" prop="sealType">
        <template slot-scope="scope">
          <el-tag style="margin:2px" type="success" v-for="(item,index) in scope.row.sealType.split(',')" :key="index">
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请日期" align="center" prop="createTime" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" width="180" align="center" prop="submitTime"/>
      <el-table-column label="最后修改时间" width="180" align="center" prop="lastUpdateTime"/>
      <el-table-column
        label="科室审核意见"
        align="center"
        prop="deptIdea"
        width="90"
      >
        <template slot-scope="{row}">
          <el-tag
            type="info"
            v-show="row.deptIdea==='0'"
          >
            未审批
          </el-tag>
          <el-tag
            type="success"
            v-show="row.deptIdea==='1'"
          > 同意
          </el-tag>
          <el-tag
            type="danger"
            v-show="row.deptIdea==='2'"
          > 不同意
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="科室审批时间" width="160" align="center" prop="deptMasterTime"/>
      <el-table-column
        label="用印审批人意见"
        align="center"
        prop="sealIdea"
        width="90"
      >
        <template slot-scope="{row}">
          <el-tag
            type="info"
            v-show="row.sealIdea==='0'"
          >
            未审批
          </el-tag>
          <el-tag
            type="success"
            v-show="row.sealIdea==='1'"
          > 同意
          </el-tag>
          <el-tag
            type="danger"
            v-show="row.sealIdea==='2'"
          > 不同意
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="用印负责人审核时间" width="160" align="center" prop="sealMasterTime"/>
      <el-table-column
        label="申请状态"
        align="center"
        prop="deleted"
        width="120"
      >
        <template slot-scope="{row}">
          <el-tag
            type="primary"
            v-show="row.deleted===0"
          >
            未审批
          </el-tag>
          <el-tag
            type="primary"
            v-show="row.deleted===1"
          > 审核中
          </el-tag>
          <el-tag
            type="primary"
            v-show="row.deleted===2"
          > 审批完成
          </el-tag>
          <el-tag
            type="primary"
            v-show="row.deleted===3"
          > 用户已取消
          </el-tag>
          <el-tag
            type="warning"
            v-show="row.deleted===4"
          > 退回修改
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['seal:seal:query']"
          >修改
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-folder-add"
            @click="handleUpload(scope.row)"
            v-hasPermi="['seal:seal:reUpFile']"
            v-show="scope.row.deleted===2"
          >补传附件
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleView(scope.row)"
            v-hasPermi="['seal:seal:query']"
          >查看
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['seal:seal:remove']"
          >取消
          </el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用印对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="18" :offset="1">
            <el-form-item label="申请人姓名" prop="userName">
              <el-input :disabled="true" v-model="form.userName" placeholder="请输入申请人姓名"/>
            </el-form-item>
            <el-form-item label="申请人部门" prop="userDept">
              <el-input :disabled="true" dashed v-model="form.userDept" placeholder="请输入申请人部门"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="1">
            <el-form-item label="科室负责人" prop="deptMasterId">
              <el-select
                class="ele-block"
                v-model.number="form.deptMasterId"
                placeholder="请选择科室负责人"
                style="width: 250px"
              >
                <el-option
                  v-for="item in deptMasterList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用印批准人" prop="sealMasterId">
              <el-select
                class="ele-block"
                v-model.number="form.sealMasterId"
                placeholder="请选择用印批准人"
                style="width: 250px"
              >
                <el-option
                  v-for="item in sealMasterList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用印类型:" prop="sealType">
              <el-select
                multiple
                class="ele-block"
                v-model="form.sealType"
                placeholder="请选择用印类型"
              >
                <el-option
                  v-for="item in sealTypeList"
                  :key="item.sealTypeId"
                  :label="item.sealTypeName"
                  :value="item.sealTypeName"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="申请日期" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                align="right"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="标题或事由" prop="sealTitle">
              <el-input v-model="form.sealTitle" placeholder="请输入标题或事由"/>
            </el-form-item>
            <el-form-item label="发送单位" prop="sentDept">
              <el-input v-model="form.sentDept" placeholder="请输入发送单位"/>
            </el-form-item>
            <el-form-item label="上传附件" prop="sealFile">
              <file-upload :limit="20" :fileSize="50" v-model="form.sealFile"/>
            </el-form-item>
            <el-form-item label="文件份数" prop="fileNum">
              <el-input-number v-model="form.fileNum" :precision="0" controls-position="right" :min="0"
                               :step="1"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23" :offset="1">
            <el-form-item label="申请人备注" prop="userRemarks">
              <el-input v-model="form.userRemarks" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 补传附件对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="openUpload"
      width="700px"
      append-to-body
    >
      <el-form
        ref="uploadForm"
        :model="uploadForm"
        label-width="120px"
      >
        <el-form-item label="附件证明" prop="sealFile">
          <file-upload v-model="uploadForm.sealFile"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateSealFile">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSeal,
  delSeal,
  addSeal,
  querySealType,
  exportOwnSelectedSealList,
  getSeal,
  updateSelfSeal, reUpFile
} from '@/api/seal/seal'
import log from '@/views/monitor/job/log'
import { updateAttachment } from '@/api/out/leave'

export default {
  name: 'Seal',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用印表格数据
      sealList: [],
      // 用印类型数据
      sealTypeList: [],
      //已选择用印数据
      sealTypeValue: [],
      //部门负责人下拉列表数据
      deptMasterList: [],
      sealMasterList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //补传附件弹出层
      openUpload: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sealId: null,
        userName: null,
        sealTitle: null,
        deptIdea: null,
        sealIdea: null,
        ids: null
      },
      // 表单参数
      form: {},
      //补传文件参数
      uploadForm: {},
      deptIdeaOptions: [
        {
          id: 1,
          value: '0',
          label: '未审核'
        },
        {
          id: 2,
          value: '1',
          label: '同意'
        },
        {
          id: 3,
          value: '2',
          label: '不同意'
        }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '申请人姓名不能为空', trigger: 'blur' }
        ],
        userDept: [
          { required: true, message: '申请人部门不能为空', trigger: 'blur' }
        ],
        sealType: [{
          required: true, message: '用印类型不能为空', trigger: 'change'
        }],
        sentDept: [{ required: true, message: '发送单位不能为空', trigger: 'blur' }],
        createTime: [
          { required: true, message: '申请日期不能为空', trigger: 'change' }],
        sealTitle: [
          { required: true, message: '标题或事由不能为空', trigger: 'blur' }],
        deptMasterId: [
          { required: true, message: '科室负责人不能为空', trigger: 'change' }],
        sealMasterId: [
          { required: true, message: '用印批准人不能为空', trigger: 'change' }],
        fileNum: [
          { required: true, message: '文件份数不能为空', trigger: 'blur' }],
        sealFile: [{ required: true, message: '附件不能为空', trigger: 'blur' }]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '明天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }]
      }
    }
  },
  created() {
    this.getList()
  },
  //监听
  watch: {
    'form.sealFile': function(val) {
      if (val != null) {
        this.form.fileNum = val.split(',').length
      }
    }
  },
  methods: {
    /** 查询用印列表 */
    getList() {
      this.loading = true
      listSeal(this.queryParams).then(response => {
        this.sealList = response.rows
        this.total = response.total
        this.loading = false
      })
    }
    ,
    // 取消按钮
    cancel() {
      this.open = false
      this.openUpload = false
      this.reset()
    }
    ,
    // 表单重置
    reset() {
      this.form = {
        sealId: null,
        userId: null,
        userName: null,
        userDept: null,
        sealType: null,
        createTime: null,
        sentDept: null,
        sealTitle: null,
        sealFile: null,
        handledby: null,
        fileNum: null,
        deptMaster: null,
        deptIdea: null,
        deptRemarks: null,
        sealMaster: null,
        sealIdea: null,
        sealRemarks: null,
        userRemarks: null,
        deleted: null,
        deptMasterId: undefined,
        sealMasterId: undefined
      }
      this.resetForm('form')
      this.sealTypeValue = []
      //重置表单
      this.uploadForm = {}
    }
    ,
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    }
    ,
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
    ,
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sealId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
    ,
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      querySealType().then(response => {
        this.sealTypeList = response.data.sealType
        this.form.userName = response.data.nickName
        this.form.userDept = response.data.deptName
        this.sealMasterList = response.data.sealMaster.map((item) => {
          return {
            value: parseInt(`${item.user_id}`),
            label: `id: ${item.user_id} 姓名: ${item.nick_name}`,
            key: parseInt(`${item.user_id}`)
          }
        })
        this.deptMasterList = response.data.deptMaster.map((item) => {
          return {
            value: parseInt(`${item.user_id}`),
            label: `id: ${item.user_id} 姓名: ${item.nick_name}`,
            key: parseInt(`${item.user_id}`)
          }
        })
      })
      this.open = true
      this.title = '用印申请'
    }
    ,
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      Promise.all([
        querySealType().then(response => {
          this.sealTypeList = response.data.sealType
          this.form.userName = response.data.nickName
          this.form.userDept = response.data.deptName
          this.sealMasterList = response.data.sealMaster.map((item) => {
            return {
              value: parseInt(`${item.user_id}`),
              label: `id: ${item.user_id} 姓名: ${item.nick_name}`,
              key: parseInt(`${item.user_id}`)
            }
          })
          this.deptMasterList = response.data.deptMaster.map((item) => {
            return {
              value: parseInt(`${item.user_id}`),
              label: `id: ${item.user_id} 姓名: ${item.nick_name}`,
              key: parseInt(`${item.user_id}`)
            }
          })
        }),
        getSeal(row.sealId).then(response => {
          this.form = response.data
          if (this.form.sealType != null) {
            this.form.sealType = this.form.sealType.split(',')
          }
          this.form.sealMasterId = parseInt(response.data.sealMasterId)
          this.form.deptMasterId = parseInt(response.data.deptMasterId)
        })
      ])

      this.open = true
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          //多选框数据处理
          let s = []
          for (var i = 0; i < this.form.sealType.length; i++) {
            s.push(this.form.sealType[i])
          }
          this.form.sealType = s.join()
          let params = Object.assign({}, this.form)

          if (this.form.sealId != null) {
            updateSelfSeal(params).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addSeal(params).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    }
    ,
    /** 查看按钮跳转操作 */
    handleView(row) {
      this.$router.push({ path: '/ViewSealExcel', query: { sealId: row.sealId } })
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const sealIds = row.sealId || this.ids
      if (row.deleted === 3) {
        this.$modal.msgError('当前申请已取消')
      } else {
        this.$modal.confirm('是否确认删除用印编号为"' + sealIds + '"的数据项？').then(function() {
          return delSeal(sealIds)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      }
    }
    ,
    /** 导出按钮操作 */
    handleExport() {
      /*    const queryParams = this.ids
         this.$confirm('是否确认导出选中的数据项?', '警告', {
           confirmButtonText: '确定',
           cancelButtonText: '取消',
           type: 'warning'
         }).then(function() {
           return exportOwnSelectedSealList(queryParams)
         }).then(response => {
           this.download(response.msg, `seal.xlsx`)
         }) */
      this.queryParams.ids = this.ids
      this.download('/seal/exportOwnSelectedSealList', {
        ...this.queryParams
      }, `用印申请导出数据_${new Date().getTime()}.xlsx`)
    },

    /** 打开上传对话框 */
    handleUpload(row) {
      this.openUpload = true
      this.title = '上传附件'
      this.uploadForm.sealFile = row.sealFile
      this.uploadForm.sealId = row.sealId
      this.uploadForm.userId = row.userId
    },

    /** 上传文件 */
    updateSealFile() {
      this.$refs['uploadForm'].validate((valid) => {
        if (valid) {
          //提交到后台
          reUpFile(this.uploadForm)
            .then((response) => {
              this.$modal.msgSuccess('上传成功')
              this.openUpload = false
              this.getList()
            })
            .catch(() => {
              this.$message.error('上传失败')
            })
        }
      })
    }

  }
}
</script>
